<?php

namespace app\controller;

use support\Request;
use Kingbes\Attribute\Annotation;
use app\validate\TableValidate;
use app\model\Options;
use app\common\Tool;
use think\facade\Db;

#[Annotation(title: "数据库", auth: true)]
class TableController
{
    #[Annotation(title: "查询", view: true)]
    public function query(Request $request)
    {
        // 提交
        if ($request->method() === "POST") {
            // 数据
            $param = $request->all();
            // 查询
            $res = Options::where("name", "like", "table_form_%")
                ->paginate([
                    "page" => $param["page"],
                    "list_rows" => $param["limit"],
                ]);
            // 数据整理
            $data = $res->toArray()["data"];
            foreach ($res->toArray()["data"] as $k => $v) {
                $arr = json_decode($v["value"], 320);
                $sql = Tool::getTable($arr["table"]);
                $query = Db::query($sql);
                $data[$k]["TABLE_NAME"] = $query[0]["TABLE_NAME"];
                $data[$k]["ENGINE"] = $query[0]["ENGINE"];
                $data[$k]["TABLE_COMMENT"] = $query[0]["TABLE_COMMENT"];
                $data[$k]["AUTO_INCREMENT"] = $query[0]["AUTO_INCREMENT"];
            }
            // 返回
            return json([
                "code" => 0,
                "msg" => "获取成功",
                "count" => $res->total(),
                "data" => $data,
            ]);
        }
        // 模板渲染
        return fetch();
    }

    #[Annotation(title: "新增", view: true, auth: true)]
    public function add(Request $request)
    {
        // 提交
        if ($request->method() === "POST") {
            // 数据
            $param = $request->all();
            try {
                // 验证
                validate(validate: TableValidate::class, scene: "add", data: $param);
                // 数据处理
                $data = [
                    "table" => $param["table"],
                    "COMMENT" => $param["COMMENT"]
                ];
                unset($param["table"], $param["COMMENT"]);
                $data["data"] = $param;
                $table = Tool::createTable($data);
                // 新增
                Db::startTrans();
                try {
                    Options::create([
                        "name" => "table_form_" . $data["table"],
                        "value" => json_encode($data, 320)
                    ]);
                    Db::query($table);
                    // 提交事务
                    Db::commit();
                    // 返回
                    return success(msg: "新增成功");
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return error($e->getMessage());
                }
            } catch (\think\exception\ValidateException $e) {
                // 返回验证错误
                return error(
                    msg: $e->getError()["msg"],
                    data: $e->getError()["key"]
                );
            }
        }
        // 渲染
        return fetch();
    }

    #[Annotation(title: "编辑", auth: true)]
    public function edit(Request $request)
    {
        // 查找
        $find = Options::find($request->get("id"));
        // 赋值模板
        assign("find", json_decode($find["value"], true));
        // 提交
        if ($request->method() === "POST") {
            // 数据
            $param = $request->all();
            try {
                // 验证
                validate(validate: TableValidate::class, scene: "edit", data: $param);
                // 数据处理
                $data = [
                    "table" => $param["table"],
                    "COMMENT" => $param["COMMENT"]
                ];
                unset($param["table"], $param["COMMENT"]);
                $data["data"] = $param;
                $res = Options::update([
                    "id" => $param["id"],
                    "name" => "table_form_" . $data["table"],
                    "value" => json_encode($data, 320)
                ]);
                // 返回
                return success(msg: "操作成功", data: $res);
            } catch (\think\exception\ValidateException $e) {
                // 返回验证错误
                return error(
                    msg: $e->getError()["msg"],
                    data: $e->getError()["key"]
                );
            }
        }
        // 渲染
        return fetch();
    }
}
